package com.java.servlet;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-09-09 1:36
 * @Modified By:
 */
@WebServlet(value = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1创建上传对象
        SmartUpload smartUpload = new SmartUpload();
        //2初始化
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 5, true);
        smartUpload.initialize(pageContext);
        //3设置编码方式
        smartUpload.setCharset("utf-8");
        //4.上传
        try {
            smartUpload.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5.保证文件信息
        File file = smartUpload.getFiles().getFile(0);
        //6.得到文件名保存文件信息
        String fileName = file.getFileName();
        //7.指定服务器保存文件的路径
        String url = "uploadFile/"+fileName;
        try {
            file.saveAs(url,File.SAVEAS_VIRTUAL);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //8.判断是否保存成功
        req.setAttribute("filename",fileName);
        String uname = smartUpload.getRequest().getParameter("uname");
        System.out.println(uname);
        //9.跳转页面(转发)
        req.getRequestDispatcher("/success.jsp").forward(req,resp);
    }
}
